package com.sfx.concurrent.demo.concurrent.AlternatingOutput;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-14
 * Time: 11:06
 */

public class demo1 {
    public static void main(String[] args) {
        WaitNotify wn = new WaitNotify(1,5);
        new Thread(()->{
            wn.print("a",1,2);
        },"t1").start();
        new Thread(()->{
            wn.print("b",2,3);
        },"t2").start();
        new Thread(()->{
            wn.print("c",3,1);
        },"t3").start();
    }
}
class WaitNotify{
    private int flg;//等待标记,要打印的标记
    private int loopNumber;//循环打印次数

    public WaitNotify(int flg, int loopNumber) {
        this.flg = flg;
        this.loopNumber = loopNumber;
    }

    // str : 当前应该打印的字符
    // waitFlg : 此时的标记与要打印的标记相等(waitFlg==flg),那么表示要开始打印str
    // nextFlg : 打印完当前字符之后,接下来该打印标记为nextFlg
    // str  waitFlg  nextFlg
    //  a    1         2
    //  b    2         3
    //  c    3         1
    public void print(String str,int waitFlg,int nextFlg) {
        for(int i =0;i<loopNumber;++i) {
            synchronized (this) {
                while(waitFlg!=flg) {//条件不成立一直等待
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //条件成立,打印当前字符串str,并设置下一个打印标记,唤醒其他线程
                System.out.print(str);//打印当前字符串str,
                flg = nextFlg;//设置下一个打印标记
                this.notifyAll();//唤醒其他线程
            }
        }
    }
}